<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>更新页面</title>
        <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
        <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />

        <style>
            .tags-container {
                display: flex;
                flex-wrap: wrap;
                gap: 5px;
                border: 1px solid #e6e6e6;
                padding: 5px;
                border-radius: 4px;
            }
            .tag {
                background-color: #009688;
                color: white;
                padding: 5px 10px;
                border-radius: 3px;
                display: flex;
                align-items: center;
            }
            .tag .remove {
                margin-left: 5px;
                cursor: pointer;
            }
        </style>
    </head>
    <body>

        <form class="layui-form">

            <div class="mainBox">
                <div class="main-container mr-5">

                    <div class="layui-form-item">
                        <label class="layui-form-label">作品名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" value="" readonly class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">作品主图</label>
                        <div class="layui-input-block">
                            <img id="thumb-preview" src="/path/to/thumb.jpg" alt="作品主图" style="max-width: 200px; cursor: pointer;" onclick="openImagePreview(this.src)">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">作品图集</label>
                        <div class="layui-input-block" id="images-preview">
                        </div>
                    </div>


                    <div class="layui-form-item">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="status" lay-skin="switch" lay-text="审核通过|未通过">
                        </div>
                    </div>


                    <div class="layui-form-item">
                        <label class="layui-form-label">审核理由</label>
                        <div class="layui-input-block">
                            <input type="text" name="reason" value="" class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">作品分类</label>
                        <div class="layui-input-block">
                            <div class="category_id" id="category_id" name="category_id"></div>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">no</label>
                        <div class="layui-input-block">
                            <input type="text" name="no" readonly value="" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">价格</label>
                        <div class="layui-input-block">
                            <input type="text" name="price" value="" class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">标签</label>
                        <div class="layui-input-block">
                            <div id="tags-container" class="tags-container">
                                <input type="text" id="tags-input" placeholder="输入标签后按回车" class="layui-input" />
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>

            <div class="bottom">
                <div class="button-container">
                    <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit="" lay-filter="save">
                        提交
                    </button>
                    <button type="reset" class="pear-btn pear-btn-md">
                        重置
                    </button>
                </div>
            </div>
            
        </form>

        <script src="/app/admin/component/layui/layui.js"></script>
        <script src="/app/admin/component/pear/pear.js"></script>
        <script src="/app/admin/admin/js/permission.js"></script>
        
        <script>

            // 相关接口
            const PRIMARY_KEY = "id";
            const SELECT_API = "/app/admin/work/select" + location.search;
            const UPDATE_API = "/app/admin/work/update";

            function openImagePreview(src) {
                layui.use('layer', function () {
                    const layer = layui.layer;
                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: 1,
                        area: ['auto', 'auto'],
                        shadeClose: true,
                        content: `<img src="${src}" style="max-width: 100%; height: auto; display: block; margin: 0 auto;">`
                    });
                });
            }

            let tags = [];

            // 获取数据库记录
            layui.use(["form", "util", "popup", "jquery"], function () {
                let $ = layui.$;

                const tagsInput = $('#tags-input');
                const tagsContainer = $('#tags-container');

                // 存储标签

                // 添加标签
                tagsInput.on('keypress', function (e) {
                    if (e.which === 13) { // 按下回车键
                        e.preventDefault();
                        const tag = tagsInput.val().trim();
                        if (tag && !tags.includes(tag)) {
                            tags.push(tag);
                            renderTags();
                            tagsInput.val('');
                        }
                    }
                });

                // 删除标签
                tagsContainer.on('click', '.remove', function () {
                    const tag = $(this).data('tag');
                    tags = tags.filter(t => t !== tag);
                    renderTags();
                });

                // 渲染标签
                function renderTags() {
                    tagsContainer.find('.tag').remove();
                    tags.forEach(tag => {
                        const tagElement = $(`<div class="tag">${tag}<span class="remove" data-tag="${tag}">×</span></div>`);
                        tagsContainer.append(tagElement);
                    });
                }

                $.ajax({
                    url: SELECT_API,
                    dataType: "json",
                    success: function (res) {
                        
                        // 给表单初始化数据
                        layui.each(res.data[0], function (key, value) {
                            let obj = $('*[name="'+key+'"]');
                            if (key === "password") {
                                obj.attr("placeholder", "不更新密码请留空");
                                return;
                            }

                            if (key === "tags") {
                                tags = JSON.parse(value);
                            }

                            if (typeof obj[0] === "undefined" || !obj[0].nodeName) return;
                            if (obj[0].nodeName.toLowerCase() === "textarea") {
                                obj.val(value);
                            }else if (obj[0].type === "checkbox" && obj.attr("lay-skin") === "switch") {
                                // 设置开关的状态
                                obj.prop("checked", Number(value) === 1);
                            }  else {
                                obj.attr("value", value);
                            }
                        });

                        // 渲染作品主图
                        if (res.data[0].thumb) {
                            const thumbPreview = document.querySelector('#thumb-preview');
                            thumbPreview.src = res.data[0].thumb; // 设置主图的 URL
                            thumbPreview.style.display = 'block'; // 显示主图
                            thumbPreview.onclick = function () {
                                openImagePreview(res.data[0].thumb); // 点击放大预览
                            };
                        }

                        // 渲染作品图集
                        if (res.data[0].images) {
                            res.data[0].images = JSON.parse(res.data[0].images);
                            const imagesPreview = document.querySelector('#images-preview');
                            imagesPreview.innerHTML = ''; // 清空之前的内容
                            res.data[0].images.forEach(image => {
                                const img = document.createElement('img');
                                img.src = image; // 设置图集图片的 URL
                                img.style.maxWidth = '100px';
                                img.style.marginRight = '10px';
                                img.style.cursor = 'pointer';
                                img.onclick = function () {
                                    openImagePreview(image); // 点击放大预览
                                };
                                imagesPreview.appendChild(img);
                            });
                        }
                        
                        // 字段 审核时间 audit_time
                        layui.use(["laydate"], function() {
                            layui.laydate.render({
                                elem: "#audit_time",
                                type: "datetime",
                            });
                        })
                        
                        // 字段 创建时间 created_time
                        layui.use(["laydate"], function() {
                            layui.laydate.render({
                                elem: "#created_time",
                                type: "datetime",
                            });
                        })
                        
                        // 字段 删除时间 delete_time
                        layui.use(["laydate"], function() {
                            layui.laydate.render({
                                elem: "#delete_time",
                                type: "datetime",
                            });
                        })
                        
                        
                        // ajax返回失败
                        if (res.code) {
                            layui.popup.failure(res.msg);
                        }


                        layui.use(["jquery", "xmSelect"], function() {
                            layui.$.ajax({
                                url: "/app/admin/work-category/get",
                                dataType: "json",
                                success: function (res) {
                                    let value = layui.$("#category_id").attr("value");
                                    let initValue = value ? value.split(",") : [];
                                    layui.xmSelect.render({
                                        // tree: {
                                        //     show: true,
                                        //     strict: false,
                                        // },
                                        el: "#category_id",
                                        name: "category_id",
                                        initValue: initValue,
                                        data: res.data,
                                        clickClose: true,
                                        radio: true,
                                        filterable: true,
                                        model: {"icon":"hidden","label":{"type":"text"}},
                                    });
                                    if (res.code) {
                                        return layui.popup.failure(res.msg);
                                    }
                                }
                            });
                        });

                        renderTags()

                        layui.form.render();
                    }
                });
            });

            //提交事件
            layui.use(["form", "popup"], function () {
                // 字段验证允许为空
                layui.form.verify({
                    phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
                    email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
                    url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
                    number: [/(^$)|^\d+$/,'只能填写数字'],
                    date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
                    identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
                });
                layui.form.on("submit(save)", function (data) {
                    // Explicitly handle the status field
                    const statusField = layui.$('*[name="status"]');
                    data.field.status = statusField.prop("checked") ? 1 : 2;
                    data.field.tags = JSON.stringify(tags)

                    data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];

                    layui.$.ajax({
                        url: UPDATE_API,
                        type: "POST",
                        dateType: "json",
                        data: data.field,
                        success: function (res) {
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                parent.refreshTable();
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                            });
                        }
                    });
                    return false;
                });
            });

        </script>

    </body>

</html>
